import fs from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'

const parentDir = path.resolve("./plugins/BH3-Plugin", "..")
const dealEventPath = path.join(parentDir, "genshin", "apps", "dealEvent.js")
const isDealEventMissing = !fs.existsSync(dealEventPath)
const appDir = path.resolve('./plugins/BH3-Plugin/apps')
const files = fs.readdirSync(appDir).filter(file => file.endsWith('.js'))

let ret = []
for (const file of files) {
  const filePath = path.join(appDir, file)
  ret.push(import(pathToFileURL(filePath).href))
}

ret = await Promise.allSettled(ret)

let apps = {}
for (let i in files) {
  const name = files[i].replace('.js', '')

  if (ret[i].status !== 'fulfilled') {
    logger.error(`载入插件错误：${logger.red(name)}`)
    logger.error(ret[i].reason)
    continue
  }

  const moduleExports = ret[i].value
  apps[name] = moduleExports.default || moduleExports[Object.keys(moduleExports)[0]]
}

if (isDealEventMissing) {
  try {
    const indexPath = path.join(appDir, 'index.js')
    const indexModule = await import(pathToFileURL(indexPath).href)
    apps.dealEvent = indexModule.default || indexModule[Object.keys(indexModule)[0]]
    logger.mark(`检测到原神目录缺少 dealEvent.js，已加载备用模块: ${logger.blue('index.js')}`)
  } catch (e) {
    logger.error(`加载备用模块失败: ${logger.red('index.js')}`)
    logger.error(e.stack)
  }
}

export { apps }
